package cc.coopersoft.keycloak.phone.providers.sender;

import cc.coopersoft.keycloak.phone.providers.constants.TokenCodeType;
import cc.coopersoft.keycloak.phone.providers.exception.MessageSendException;
import cc.coopersoft.keycloak.phone.providers.spi.MessageSenderService;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.jboss.logging.Logger;

import static cc.coopersoft.keycloak.phone.providers.constants.TokenCodeType.REGISTRATION;

public class AliyunSmsSenderServiceProvider implements MessageSenderService {

  private static final Logger logger = Logger.getLogger(AliyunSmsSenderServiceProvider.class);


  static final String accessKeyId = "";
  static final String accessKeySecret = "";

  @Override
  public void sendSmsMessage(TokenCodeType type, String phoneNumber, String code, int expires, String kind) throws MessageSendException {
    IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
    IAcsClient client = new DefaultAcsClient(profile);
    logger.info("key:" + accessKeyId + "   " + "secret:" + accessKeySecret);
    CommonRequest request = new CommonRequest();
    request.setSysMethod(MethodType.POST);
    request.setSysDomain("dysmsapi.aliyuncs.com");
    request.setSysAction("SendSms");
    request.setSysVersion("2017-05-25");
    request.putQueryParameter("PhoneNumbers", phoneNumber);
    request.putQueryParameter("SignName", "");
    if(REGISTRATION.equals(type)) {
      request.putQueryParameter("TemplateCode", "");
    } else {
      request.putQueryParameter("TemplateCode", "");
    }
    request.putQueryParameter("TemplateParam", String.format("{\"code\":\"%s\"}",code));
    try {
      CommonResponse response = client.getCommonResponse(request);
      logger.info(response.getData());
    } catch (ClientException e) {
      throw new MessageSendException(500,e.getErrCode(),e.getMessage());
    }
  }

  @Override
  public void close() {

  }
}
